package com.ruoyi.manage.controller;

import java.util.List;
import java.util.Map;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.manage.domain.CrInterviewSlot;
import com.ruoyi.manage.service.ICrInterviewSlotService;

/**
 * 面试时段Controller
 * 
 * @author ruoyi
 * @date 2024-09-24
 */
@RestController
@RequestMapping({"/campus/interviewSlot", "/campus/student"})
public class CrInterviewSlotController extends BaseController
{
    @Autowired
    private ICrInterviewSlotService crInterviewSlotService;

    /**
     * 处理根路径访问
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:list') or @ss.hasRole('club')")
    @GetMapping
    public AjaxResult index()
    {
        // 根路径访问可以返回一个基本信息或重定向到列表页面
        return AjaxResult.success("访问面试时段管理页面成功");
    }
    
    /**
     * 查询面试时段列表
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:list')")
    @GetMapping("/list")
    public TableDataInfo list(CrInterviewSlot crInterviewSlot)
    {
        startPage();
        List<CrInterviewSlot> list = crInterviewSlotService.selectCrInterviewSlotList(crInterviewSlot);
        return getDataTable(list);
    }

    /**
     * 导出面试时段列表
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:export')")
    @Log(title = "面试时段", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CrInterviewSlot crInterviewSlot)
    {
        List<CrInterviewSlot> list = crInterviewSlotService.exportInterviewSlots(crInterviewSlot);
        ExcelUtil<CrInterviewSlot> util = new ExcelUtil<CrInterviewSlot>(CrInterviewSlot.class);
        util.exportExcel(response, list, "面试时段数据");
    }

    /**
     * 获取面试时段详细信息
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:query') or @ss.hasRole('club')")
    @GetMapping(value = "/{slotId}")
    public AjaxResult getInfo(@PathVariable("slotId") Long slotId)
    {
        return success(crInterviewSlotService.selectCrInterviewSlotBySlotId(slotId));
    }

    /**
     * 新增面试时段
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:add')")
    @Log(title = "面试时段", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrInterviewSlot crInterviewSlot)
    {
        return toAjax(crInterviewSlotService.insertCrInterviewSlot(crInterviewSlot));
    }

    /**
     * 修改面试时段
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:edit')")
    @Log(title = "面试时段", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CrInterviewSlot crInterviewSlot)
    {
        return toAjax(crInterviewSlotService.updateCrInterviewSlot(crInterviewSlot));
    }

    /**
     * 删除面试时段
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:remove') or @ss.hasRole('club')")
    @Log(title = "面试时段", businessType = BusinessType.DELETE)
	@DeleteMapping("/{slotIds}")
    public AjaxResult remove(@PathVariable Long[] slotIds)
    {
        return toAjax(crInterviewSlotService.deleteCrInterviewSlotBySlotIds(slotIds));
    }

    // ========== 业务相关接口 ==========

    /**
     * 创建面试时段
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:add') or @ss.hasRole('club')")
    @Log(title = "创建面试时段", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public AjaxResult createInterviewSlot(@RequestBody Map<String, Object> params)
    {
        Long clubId = Long.valueOf(params.get("clubId").toString());
        Long recruitmentId = params.get("recruitmentId") != null ? 
            Long.valueOf(params.get("recruitmentId").toString()) : null;
        
        // 处理日期时间字符串转换
        String startTimeStr = (String) params.get("startTime");
        String endTimeStr = (String) params.get("endTime");
        Date startTime = null;
        Date endTime = null;
        
        try {
            // 处理可能包含星期的时间格式，例如：'yyyy-10-We 18:04:02'
            if (startTimeStr != null && startTimeStr.contains("-We ")) {
                // 提取日期部分（去掉星期）
                startTimeStr = startTimeStr.replaceAll("-[A-Za-z]{2} ", " ");
            }
            if (endTimeStr != null && endTimeStr.contains("-We ")) {
                // 提取日期部分（去掉星期）
                endTimeStr = endTimeStr.replaceAll("-[A-Za-z]{2} ", " ");
            }
            
            // 尝试解析标准格式: yyyy-MM-dd HH:mm:ss
            startTime = DateUtils.parseDate(startTimeStr);
            endTime = DateUtils.parseDate(endTimeStr);
        } catch (Exception e) {
            return AjaxResult.error("时间格式错误，请使用标准格式：yyyy-MM-dd HH:mm:ss");
        }
        
        String location = (String) params.get("location");
        Integer maxCapacity = params.get("maxCapacity") != null ? 
            Integer.valueOf(params.get("maxCapacity").toString()) : 10;
        String description = (String) params.get("description");
        
        return toAjax(crInterviewSlotService.createInterviewSlot(
            clubId, recruitmentId, startTime, endTime, location, maxCapacity, description));
    }

    /**
     * 批量创建面试时段
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:add') or @ss.hasRole('club')")
    @Log(title = "批量创建面试时段", businessType = BusinessType.INSERT)
    @PostMapping("/batchCreate")
    public AjaxResult batchCreateInterviewSlots(@RequestBody List<CrInterviewSlot> slots)
    {
        int successCount = crInterviewSlotService.batchCreateInterviewSlots(slots);
        return success("成功创建 " + successCount + " 个面试时段");
    }

    /**
     * 根据社团ID查询面试时段
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:list') or @ss.hasRole('club')")
    @GetMapping("/club/{clubId}")
    public AjaxResult getSlotsByClub(@PathVariable Long clubId)
    {
        List<CrInterviewSlot> slots = crInterviewSlotService.selectSlotsByClubId(clubId);
        return success(slots);
    }

    /**
     * 根据招聘ID查询面试时段
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:list')")
    @GetMapping("/recruitment/{recruitmentId}")
    public AjaxResult getSlotsByRecruitment(@PathVariable Long recruitmentId)
    {
        List<CrInterviewSlot> slots = crInterviewSlotService.selectSlotsByRecruitmentId(recruitmentId);
        return success(slots);
    }

    /**
     * 查询可用的面试时段
     */
    @GetMapping("/available")
    public AjaxResult getAvailableSlots(@RequestParam Long recruitmentId, @RequestParam Date date)
    {
        List<CrInterviewSlot> slots = crInterviewSlotService.selectAvailableSlots(recruitmentId, date);
        return success(slots);
    }

    /**
     * 学生查询指定招聘的可用面试时段 - 支持前端API调用
     */
    @GetMapping("/availableSlots/{recruitmentId}")
    public AjaxResult getStudentAvailableSlots(@PathVariable Long recruitmentId)
    {
        List<CrInterviewSlot> slots = crInterviewSlotService.selectSlotsByRecruitmentId(recruitmentId);
        return success(slots);
    }

    /**
     * 检查时段冲突
     */
    @GetMapping("/checkConflict")
    public AjaxResult checkTimeConflict(@RequestParam Long clubId,
                                      @RequestParam Date startTime,
                                      @RequestParam Date endTime,
                                      @RequestParam(required = false) Long excludeSlotId)
    {
        boolean hasConflict = crInterviewSlotService.checkTimeConflict(clubId, startTime, endTime, excludeSlotId);
        return success(hasConflict);
    }

    /**
     * 更新时段容量
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:edit') or @ss.hasRole('club')")
    @PutMapping("/updateCapacity/{slotId}")
    public AjaxResult updateSlotCapacity(@PathVariable Long slotId, @RequestParam int change)
    {
        return toAjax(crInterviewSlotService.updateSlotCapacity(slotId, change));
    }

    /**
     * 获取时段的预约数量
     */
    @GetMapping("/bookingCount/{slotId}")
    public AjaxResult getSlotBookingCount(@PathVariable Long slotId)
    {
        int count = crInterviewSlotService.getSlotBookingCount(slotId);
        return success(count);
    }

    /**
     * 检查时段是否可预约
     */
    @GetMapping("/isAvailable/{slotId}")
    public AjaxResult isSlotAvailable(@PathVariable Long slotId)
    {
        boolean isAvailable = crInterviewSlotService.isSlotAvailable(slotId);
        return success(isAvailable);
    }

    /**
     * 关闭面试时段
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:edit') or @ss.hasRole('club')")
    @Log(title = "关闭面试时段", businessType = BusinessType.UPDATE)
    @PutMapping("/close/{slotId}")
    public AjaxResult closeInterviewSlot(@PathVariable Long slotId)
    {
        Long clubId = getUserId(); // 可根据实际情况调整获取方式
        return toAjax(crInterviewSlotService.closeInterviewSlot(slotId, clubId));
    }

    /**
     * 重新开放面试时段
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:edit') or @ss.hasRole('club')")
    @Log(title = "重新开放面试时段", businessType = BusinessType.UPDATE)
    @PutMapping("/reopen/{slotId}")
    public AjaxResult reopenInterviewSlot(@PathVariable Long slotId)
    {
        Long clubId = getUserId(); // 可根据实际情况调整获取方式
        return toAjax(crInterviewSlotService.reopenInterviewSlot(slotId, clubId));
    }

    /**
     * 获取社团的面试时段统计
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:list')")
    @GetMapping("/statistics/club/{clubId}")
    public AjaxResult getClubSlotStatistics(@PathVariable Long clubId)
    {
        Map<String, Object> statistics = crInterviewSlotService.getClubSlotStatistics(clubId);
        return success(statistics);
    }

    /**
     * 获取时段的详细统计
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:list')")
    @GetMapping("/statistics/{slotId}")
    public AjaxResult getSlotStatistics(@PathVariable Long slotId)
    {
        Map<String, Object> statistics = crInterviewSlotService.getSlotStatistics(slotId);
        return success(statistics);
    }

    /**
     * 查询即将开始的面试时段
     */
    @GetMapping("/upcoming")
    public AjaxResult getUpcomingSlots(@RequestParam(defaultValue = "24") int hours)
    {
        List<CrInterviewSlot> slots = crInterviewSlotService.getUpcomingSlots(hours);
        return success(slots);
    }

    /**
     * 查询已过期的面试时段
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:list')")
    @GetMapping("/expired")
    public AjaxResult getExpiredSlots()
    {
        List<CrInterviewSlot> slots = crInterviewSlotService.getExpiredSlots();
        return success(slots);
    }

    /**
     * 自动更新过期时段状态
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:edit')")
    @PutMapping("/updateExpiredStatus")
    public AjaxResult updateExpiredSlotsStatus()
    {
        int updateCount = crInterviewSlotService.updateExpiredSlotsStatus();
        return success("更新了 " + updateCount + " 个过期时段状态");
    }

    /**
     * 复制面试时段
     */
    @PreAuthorize("@ss.hasPermi('manage:interviewSlot:add')")
    @Log(title = "复制面试时段", businessType = BusinessType.INSERT)
    @PostMapping("/copy")
    public AjaxResult copyInterviewSlot(@RequestBody Map<String, Object> params)
    {
        Long sourceSlotId = Long.valueOf(params.get("sourceSlotId").toString());
        List<Date> targetDates = (List<Date>) params.get("targetDates");
        
        int successCount = crInterviewSlotService.copyInterviewSlot(sourceSlotId, targetDates);
        return success("成功复制 " + successCount + " 个面试时段");
    }
}